package cn.zymall.app.service.impl;

import cn.zymall.app.service.AdvertisingService;
import cn.zymall.common.model.Advertising;
import cn.zymall.common.utils.redis.RedisFieldItem;
import cn.zymall.common.utils.redis.RedisUtil;
import cn.zymall.common.utils.response.HttpResult;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author xuxianda
 * @Description: 广告业务层接口实现类
 * @date 2020/8/26 20:49
 * @Copyright
 * @return
 **/
@Service
public class AdvertisingServiceImpl implements AdvertisingService {

    @Autowired
    RedisUtil redisUtil;

    Gson gson = new Gson();

    @Override
    public HttpResult select() {
        Set<String> keys = redisUtil.getRedisTemplate().keys("advertising:*");
        List<Advertising> list = new ArrayList<>();
        for (String key : keys) {
            try {
                list.add(gson.fromJson((String) redisUtil.get(key), Advertising.class));
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
                continue;
            }
        }
        return new HttpResult().success("查询成功", list);
    }

    @Override
    public HttpResult save(Advertising advertising) {
        try {
            RedisFieldItem redisFieldItem = new RedisFieldItem();
            redisFieldItem.setAdKey(advertising.getAdId());
            redisFieldItem.setAdValue(gson.toJson(advertising));
            Long ms = Long.valueOf(advertising.getHour() * 60 * 1000);
            if (redisUtil.set(redisFieldItem.getAdKey(), redisFieldItem.getAdValue())) {
                redisUtil.expire(redisFieldItem.getAdKey(), ms);
                return new HttpResult().success("添加成功");
            } else {
                return new HttpResult().fail("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult().fail("系统内部错误");
        }
    }

    ;


}
